#include "viewerwidget.h"
#include "ui_viewerwidget.h"

ViewerWidget::ViewerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ViewerWidget)
{
    ui->setupUi(this);
    m_tcpServer = new QTcpServer();
    m_tcpServer->listen(QHostAddress::LocalHost, 1234);
    connect(m_tcpServer, &QTcpServer::newConnection, this, &ViewerWidget::newConnection_slot);
}

ViewerWidget::~ViewerWidget()
{
    delete ui;
}

void ViewerWidget::newConnection_slot()
{
    QTcpSocket *socket;
    socket = m_tcpServer->nextPendingConnection();
    connect(socket, &QTcpSocket::disconnected, this, &ViewerWidget::socketDisconnect_slot);
    connect(socket, &QTcpSocket::readyRead, this, &ViewerWidget::readSocket);
    m_socketList.append(socket);
}

void ViewerWidget::socketDisconnect_slot()
{
    QTcpSocket* socket = (QTcpSocket*)QObject::sender();
    m_socketList.removeOne(socket);
}

void ViewerWidget::readSocket()
{
    QTcpSocket *socket;
    QByteArray data;
    QString txt;
    socket = (QTcpSocket*)QObject::sender();
    data = socket->readAll();
    ui->textEdit->append(QString::fromLocal8Bit(data));
}
